<template>
  <div class="w-[560px]">
    <!-- <Collapsible v-model:open="isOpen">
      <collapsible-trigger as-child>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-x-2">
            <component :is="isOpen ? ChevronDown : ChevronUp" class="h-4 w-4 cursor-pointer" />
            <p>{{ title }}</p>
            <tooltip-provider>
              <tooltip>
                <tooltip-trigger>
                  <alert-circle-icon class="h-3 w-3 text-muted-foreground" />
                </tooltip-trigger>
                <tooltip-content>
                  <p class="max-w-60">
                    {{ description }}
                  </p>
                </tooltip-content>
              </tooltip>
            </tooltip-provider>
          </div>
          <component :is="properties.json.icon" :size="properties.json.size" :color="properties.json.color" />
        </div>
      </collapsible-trigger>
      <collapsible-content class="space-y-3 px-3 py-3">
        <div class="formBox">
          <div class="mt-3 flex flex-wrap items-center gap-x-2 gap-y-2">
            
            <div v-for="(item, index) in ComponentList" :key="index" :class="item.class">
              <component
                v-if="item.Options"
                :is="item.type"
                :key="item.type + '-' + index"
                :Options="isArray(item.Options)?item.Options:[{label:item.modelValue,value:item.modelValue}]"
                :placeholder="item.placeholder"
                :modelValue="item.modelValue"
                :defaultValue="item.modelValue"
                :isTree="item.isTree"
                :storeId="storeId"
                :nodeId="node.id"
                @update:modelValue="(val) => updateValueFunc(item.index, item.outputkey, val)"
              >
              </component>
              <component
                v-else
                :is="item.type"
                :key="item.type + '-else-' + index"
                :class="item.class"
                v-model="item.modelValue"
                v-on="item.handelEvent?{click:()=>item.handelEvent(storeId,nodeType)}:{}"
                @update:modelValue="(val) => updateValueFunc(item.index, item.outputkey, val)"
              >
                <template v-if="item.type == 'Label'">
                  {{ item.label }}
                </template>
              </component>
            </div>
          </div>
          <Button class="mt-2" @click.stop="handleClickAddBtn"
            ><plus-icon class="h-6 w-5 cursor-pointer text-primary" />新增</Button
          >
        </div>
      </collapsible-content>
    </Collapsible> -->
    <common-input-module :data="DLSData.input" storeId="useLLMStore" title="大模型" />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, toRaw } from 'vue'
import { ChevronsUpDownIcon, ChevronDown, ChevronUp, PlusIcon, AlertCircleIcon, MinusCircleIcon } from 'lucide-vue-next'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible'
import { useVueFlow, useNode } from '@vue-flow/core'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import { Button } from '@/components/ui/button'
import SelectComponent from '@/components/vue-flow/nodes/selectComponent.vue'
import commonInputModule from '@/components/vue-flow/common-input-module.vue'
import { cn } from '@/lib/utils'
import { useLLMDynamicCom } from '@/lib/useDynamicComponent'
import { IFormItemTypes, IEdge, IOutputItem,ReferenceOption } from '@/components/vue-flow/nodes/types/form-types'
import storeMap from '@/pina'
import {findConnectedNodes} from '@/lib/utils'
import { isArray } from 'lodash'
defineOptions({
  components: {
    Label,
    Input,
    Checkbox,
    SelectComponent,
    Textarea,
    ChevronsUpDownIcon,
    ChevronDown,
    ChevronUp,
    PlusIcon,
    AlertCircleIcon,
    MinusCircleIcon
  }
})

const isOpen = ref(true)
const node = useNode()
const { DLSData, storeId } = defineProps(['DLSData' as any, 'storeId'])
const referenceOptions = ref<ReferenceOption[]>([])
const emit = defineEmits(['onClickAddBtn'])
const LLM = storeMap.useLLMStore()
const { getEdges, getNodes,edges } = useVueFlow()
const { labels, title, description, properties, input, output } = DLSData
let ComponentList = ref<IFormItemTypes[]>([])
const updateValueFunc = (index: number, key = '', value: string) => {
  LLM.updateInputValue(index, key, value) //同步数据
}
const getDynamicComponent = (input: IOutputItem[]) => {
  const formItem = input.map((item: any, index: number) => dynamicComponent(item, index)).flat().filter(item=>item)
  ComponentList.value = [...toRaw(labels), ...formItem]
}
//渲染form表单
const dynamicComponent = (item: IOutputItem, index: number) =>{
  return Object.keys(item).map((key) => key !== 'ref' && useLLMDynamicCom(key, item, index,referenceOptions))
}

watch(input, () => {
  getDynamicComponent(input)
})

onMounted(() => {
  // handleQueryPrevNodeOutput(true)
  getDynamicComponent(input)
})

const handleClickAddBtn = () => {
  emit('onClickAddBtn', true)
}

// const handleQueryPrevNodeOutput = (flag:boolean)=>{
//   if (flag) {
//     const connectedNodes = [...findConnectedNodes(node.id,getEdges.value,getNodes.value)]
//     let selectObj = {}
//     connectedNodes.map(item=>{
//       if(item.data.output){
//         const istree = item.data.output.some((item: any) => Array.isArray(item.children) && item.children.length > 0)
//         const SelectOption = {
//           groupName:item.data.title,
//           Options:istree?item.data.output:item.data.output.map((el:any,i:number)=>{
//             return {
//               id:`${el.groupName}-${i}`,
//               label:el.name,
//               value:el.name
//             }
//           })
//         }
//         selectObj[item.data.title] = SelectOption
//       }
//     })
//     storeMap.useOptionsStore().addReferenceOption(selectObj)
//     const OptionsStore = storeMap.useOptionsStore()
//     const options = OptionsStore.referenceObject
//     referenceOptions.value = isArray(options)?options:Object.values(options)[0]?.Options
//     const nodeId = node.id;
//     const linkedNodeId = edges.value
//     .filter(edge => edge.source === nodeId || edge.target === nodeId)
//     .find(edge => edge.source === nodeId ? edge.target : edge.source)?.source;
//     linkedNodeId&&linkedNodeId&&storeMap[storeId]().updateRef(linkedNodeId)
//   }
// }
</script>

<style lang="scss" scoped>
.w-320 {
  width: 320px;
}
.w-150{
  width: 150px;
}
.w-2\/5{
  input{
    width: 100%;
  }
}
</style>
